const cmd = process.argv[2],
      filename = process.argv[3],
      fs = require('fs'),
      join = require('path').join;
      log = console.log;
let dirarr = fs.readdirSync('./sysFile');
let i = 0;

if(cmd === '-list'){
  try{
    let filearr = [];
    let size,createTime,name;
    dirarr.map(item=>{
      if(fs.statSync(`./sysFile/${item}`).isFile()){
      const stats = fs.statSync(`./sysFile/${item}`);
      size = stats.size.toString();
      createTime = Number(stats.birthtime);
      name = item;
      filearr[i] = {'filename':name,'fileSize':size,'createTime':createTime};
      i = i+1; 
    }
  });
    filearr.sort(function(obj1,obj2){
      return obj1.createTime - obj2.createTime; 
    });
    filearr.map((item,index)=>{
      const stats = fs.statSync(`./sysFile/${item.filename}`);
      filearr[index].createTime = stats.birthtime.toLocaleString();
    });
    filearr.map((item,index)=>{
      filearr[index] = JSON.stringify(item);
    });
    log(filearr);
  }catch(e){
    log(e.message);
  }
}else if(cmd === '-show'){
  try{
    if(filename !== undefined){
      fs.access(`./sysFile/${filename}`,function(err){
        log(err.code);
        if(err.code == 'ENOENT'){
          console.error(`${filename} not exists!`);
          process.exit(1);
        }
      });
      if(!fs.statSync(`./sysFile/${filename}`).isFile()){
        console.error(`${filename} is not file!`);
        process.exit(2);
      }
      const fis = fs.readFileSync(`./sysFile/${filename}`,'utf8');
      log(fis);
      process.exit(3);
   }else{
        log('not input!');
    }
  }catch(e){
    console.error(e.message);
  }
}else if(cmd === '-del'){
  try{
    if(filename !== undefined){
      fs.access(`./sysFile${filename}`,function(err){
        if(err.code == 'ENOENT'){
          console.error(`${filename} is not exist!`);
          process.exit(1);
        }
      });
      if(fs.statSync(`./sysFile/${filename}`).isFile()){
        fs.unlinkSync(`./sysFile/${filename}`);
        log(`del file ${filename} success!`);
        process.exit(5);
      }else if(fs.statSync(`./sysFile/${filename}`).isDirectory()){
        deleteDir(`./sysFile/${filename}`);
      }
    }else{
      console.error('not input!');
    }
  }catch(e){
    console.error(e.message);
  }
}
 
function deleteDir(folder){
  let files = fs.readdirSync(folder);
  for(let i=0;i<files.length;i++){
    let file = join(folder,files[i]);
    if(fs.statSync(file).isFile()){
      log(file);
      fs.unlinkSync(file);
      continue;
    }
    if(fs.statSync(file).isDirectory()){
      deleteDir(file);
    }
    fs.rmdirSync(folder);
  }
  log(`del dir ${filename} success!`);
  process.exit(5);
}

